package Review;

import java.lang.reflect.Field;

class Stu{
    private int id;
    private String name;
    private void func(){
        System.out.println("我是私有方法");
    }
    public  Stu(){
        id = 1;
        name = "叶良辰";
    }
/*    public Stu(String name){
        this.name = name;
    }*/

    @Override
    public String toString() {
        return "Stu{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
public class Reflec {
    public static void func() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class<?> c1 = Class.forName("Review.Stu");
        Field field = c1.getDeclaredField("name");
        field.setAccessible(true);
        Stu stu = (Stu)c1.newInstance();
        field.set(stu,"lisi");
        System.out.println(stu);
    }

    public static void main(String[] args) throws NoSuchFieldException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        func();

    }
    public static void main3(String[] args) throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class<?> c1 = Class.forName("Review.Reflec");
        Field field = c1.getDeclaredField("name");
        field.setAccessible(true);
        Stu stu = (Stu)c1.newInstance();
        field.set(stu,"lisi");
        System.out.println(stu);
    }
    public static void main2(String[] args) {
        Stu stu = new Stu();
        System.out.println(stu.toString());
    }
    public static void main1(String[] args) {
        //反射获取对象常见的有三种方法
        //1.通过对象的getClass方法
        //要通过对象,首先要创建对象
        Stu stu = new Stu();
        Class<?> c1 = stu.getClass();
        //通过类名.class
        Class<?> c2 = Stu.class;
        //通过forname
        Class<?> c3;

        {
            try {
                c3 = Class.forName("Review.Reflec");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
//        System.out.println(c1.equals(c2));
//        System.out.println(c1 == c2);
        Stu stu1 = null;
        try {
            stu1 = (Stu) c1.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        System.out.println(stu1.toString());

    }

}
